package com.nettywork.splitpacket;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class MyProtocolDecoder extends ByteToMessageDecoder {

    private int length = 0;

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        System.out.println("自定义解码器调用: MyProtocolDecoder");
        System.out.println("需要解码的数据包对象: " + byteBuf);
        if(byteBuf.readableBytes() >= 4){
            if(length == 0){
                length = byteBuf.readInt();
            }
            if(byteBuf.readableBytes() < length){
                System.out.println("当前数据不完整,继续等待数据发送");
                return;
            }
            System.out.println("解码客户端发送的数据 封装成 MyProtocol 对象");
            byte[] content = new byte[length];
            if(byteBuf.readableBytes() >= length){
                 byteBuf.readBytes(content);
                 MyProtocol myProtocol = new MyProtocol();
                 myProtocol.setLen(length);
                 myProtocol.setContent(content);
                 list.add(myProtocol);
            }
            length = 0;
        }
    }
}
